local log = require("log")
local ui = require("ui")
local audio = require("audio")
local http = require("socket.http")
local ltn12 = require("ltn12")
local lfs = require("lfs")

local g_musics = {}

local function find_audio_file(filePath, musics)
  for file in lfs.dir(filePath) do
    if file ~= "." and file ~= ".." then
      local f = filePath .. "/" .. file
      local attr = lfs.attributes(f)
      assert(type(attr) == "table")
      if attr.mode == "directory" then
        find_audio_file(f, musics)
      else
        table.insert(musics, f)
      end
    end
  end
end

return {
  init = function()
    log.debug("init called")
    -- ui.main_window_open()
    --    ui.theme_light()
    ui.main_window_change_bg(0.2, 0, 0.1, 1)
    log.debug("init end")

    -- local rbody = ""
    -- local rawbody = {}
    -- local r, c, h = http.request({
    --   url = "http://192.168.31.9:3000/",
    --   method = "GET",
    --   sink = ltn12.sink.table(rawbody),
    -- })
    -- log.debug("r: " .. tostring(r))
    -- log.debug("c: " .. tostring(c))
    -- log.debug("h: " .. tostring(h))
    -- if c == 200 then
    --   rbody = table.concat(rawbody)
    --   log.debug(rbody)
    -- end
    --

    find_audio_file("./audio", g_musics)
    -- ui.main_window_loop()
  end,
  update = function(width, height)
    if ui.window_begin("窗体", width, height) then
      ui.separator_text('背景色')
      if ui.button("背景 1") then
        ui.main_window_change_bg(0.2, 0, 0.1, 1)
      end
      ui.sameline()
      if ui.button("背景 2") then
        ui.main_window_change_bg(0.7, 0.4, 0.1, 1)
      end
      ui.separator_text('theme')
      if ui.button("theme dark") then
        ui.theme_dark()
      end
      ui.sameline()
      if ui.button("theme light") then
        ui.theme_light()
      end
      ui.sameline()
      if ui.button("theme classic") then
        ui.theme_classic()
      end
      if ui.color_button("reload all") then
        local reload = _G["copi_env_reload"]
        reload()
      end
      ui.separator_text('music list')
      if ui.color_button("stop music") then
        audio.stop()
      end
      for k, v in ipairs(g_musics) do
        if ui.button(k .. " " .. v) then
          audio.play(v)
        end
      end
    end
    ui.window_end()
  end,
}
